#include <unistd.h>
#include <fcntl.h>
#include<string.h>
#include<errno.h>
#include<stdio.h>
void set_fl(int fd, int flags)
{
    int val;
    if((val = fcntl(fd,F_GETFL,0))<0)
        printf("fcntl F_GETFL error:%s",strerror(errno));

    val |= flags;//开启标识
    //val &= ~flags;//关闭标识

    if(fcntl(fd,F_SETFL,val)<0)
        printf("fcntl F_SETFL error:%s",strerror(errno));
}

//实现与dup2功能相同的函数代码：
int my_dup2(int oldfd,int newfd){
    if(newfd == oldfd){
        return newfd;
    }
    close(newfd);
    int new_fd = oldfd;
    while(new_fd<newfd){
        new_fd = dup(new_fd);
        if(new_fd == -1){
            perror("dup");
            return -1;
        }
    }
    return newfd;
}

//用lseek从文件的任意位置开始读取：
int main()
{
    int fd = open("text.txt",O_RDWR|O_APPEND);
    if(fd == -1){
        perror("lseek");
        return 1;
    }
    off_t offest = 5;
    if(lseek(fd,offest,SEEK_SET)==-1)
    {
        perror("lseek");
        close(fd);
        return 1;
    }
    char buffer[10];
    ssize_t bytes_read = read(fd,buffer,sizeof(buffer));
    if(bytes_read == -1)
    {
        perror("read");
        close(fd);
        return 1;
    }

    buffer[bytes_read] = 0;
    printf("Read data: %s\n",buffer);
    close(fd);
    return 0;
}